package de.koller.million.grid.engine.player;

import de.koller.million.grid.engine.EngineRoot;
import de.koller.million.grid.engine.enc.Encounter;
import de.koller.oceanFramework.OceanException;
import de.koller.oceanFramework.util.MIn;
import de.koller.oceanFramework.util.MOut;
import java.util.HashSet;
import java.util.Set;

public class Player {
	
	public final EngineRoot engineRoot;
	
	public final String name;
	public final PlayerStats playerStats = new PlayerStats();
	private Set<Integer> grp = new HashSet<>();
	
	private Encounter encounter = null;
	
	public Player( String name, EngineRoot engineRoot ) {
		this.name = name;
		this.engineRoot = engineRoot;
	
		this.load();
		playerStats.damage.joinAdd( "default", 1 );
		playerStats.healthPoints.joinAdd( "default", 100 );
		playerStats.foodGen.joinAdd( "default", 1 );
		playerStats.speed.joinAdd( "default", 0.1 );
	}

	public void step( int elapsedTime ) {
		if( encounter != null )
			return;
			
		foodGen();
	}
	
	public boolean isEncounterReady() {
		if( encounter != null )
			return false;
		return playerStats.getCurrentHP() == playerStats.healthPoints.getValue();
	}
	
	private void foodGen() {
		playerStats.addHP( playerStats.foodGen.getValue() );
	}
	
	public void load() {
		MIn in = new MIn( "./grid/player/p_" + name );
		in.readString( 1 );
		
		int grpn = in.readInt( 1 )[0];
		for( int i = 0; i < grpn; i++ )
			grp.add( in.readInt( 1 )[0] );
		in.close();
	}
	
	public void save() {
		MOut out = new MOut( "./grid/player/p_" + name );
		out.writeString( name );
		
		out.writeInt( grp.size() );
		for( Integer i : grp )
			out.writeInt( i );
		
		out.close();
	}

	public void setEncounter( Encounter enc ) {
		if( encounter != null && enc != null )
			throw new OceanException( "Player already in an encounter!" );
		
		this.encounter = enc;
	}
	
	public Encounter getEncounter() {
		return encounter;
	}

	@Override
	public String toString() {
		return name;
	}

	public Set<Integer> getGrp() {
		return grp;
	}

	public void setGrp( int grp, boolean in ) {
		if( in )
			this.grp.add( grp );
		else
			this.grp.remove( grp );
		
		engineRoot.playerContainer.grpChanged();
	}
	
}
